package com.se.contextMenu;

import com.se.common.AIUser;
import com.se.common.ConnectionType;
import com.se.common.Message;
import com.se.common.MessageType;
import com.se.utils.ClientMessage;
import com.se.utils.ClientUtils;
import com.se.utils.ServiceUtils;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DataFormat;

import java.io.IOException;
import java.time.LocalDateTime;

import static com.se.common.Constant.DEEPSEEK_URL;
import static com.se.common.Constant.OPENAI_URL;
import static com.se.utils.ServiceUtils.*;

public class MessageContextMenu {
    public ContextMenu createMessageContextMenu(ClientMessage message) {
        ContextMenu contextMenu = new ContextMenu();

        MenuItem copyItem = new MenuItem("复制");
        MenuItem askItem = new MenuItem("询问AI");
        MenuItem downloadItem = new MenuItem("下载");

        copyItem.setOnAction(e -> {
            Clipboard clipboard = Clipboard.getSystemClipboard();
            ClipboardContent clipboardContent = new ClipboardContent();
            clipboardContent.put(DataFormat.PLAIN_TEXT, message.getContent());
            clipboard.setContent(clipboardContent);
        });

        askItem.setOnAction(e -> askAI(message.getContent()));

        downloadItem.setOnAction(e -> sendDownloadRequest(message));

        contextMenu.getItems().addAll(copyItem);

        if(message.getMsgType().equals(MessageType.MESSAGE_COMMON)
                || message.getMsgType().equals(MessageType.MESSAGE_GROUP_COMMON)) {
            contextMenu.getItems().add(askItem);
        }

        if(MessageType.MESSAGE_FILE.equals(message.getMsgType())) {
            contextMenu.getItems().add(downloadItem);
        }

        return contextMenu;
    }

    public static void sendDownloadRequest(ClientMessage item) {
        Message message = new Message();
        message.setMsgType(MessageType.MESSAGE_FILE_DOWNLOAD_REQUEST);
        message.setSendUser(item.getSendUser());
        message.setReceiveUser(item.getReceiveUser());
        message.setSendTime(item.getSendTime());
        message.setContent(item.getContent());
        try {
            ServiceUtils.createFileConnection();
        } catch (Exception e) {
            /*
            异常处理待优化
             */
            e.printStackTrace();
            return;
        }
        try {
            ClientUtils.sendMessage(ServiceUtils
                    .getConnection(ConnectionType.FILE_CONNECTION).getSocket(), message);
        } catch (IOException ex) {
                    /*
                    异常处理待优化
                     */
            ex.printStackTrace();
        }
    }

    public static void askAI(String content) {
        if(AITYPE != null && APIKEY != null && MODEL != null
                && !AITYPE.isEmpty() && !APIKEY.isEmpty() && !MODEL.isEmpty()) {
            Message msg = getAskAIMessage(content);
            try {
                ClientUtils.sendMessage(ServiceUtils
                        .getConnection(ConnectionType.BASE_CONNECTION).getSocket(), msg);
                msg = getAIReturnMessage();
                System.out.println("创建ID为: " + msg.getId() + "的消息");
                ServiceUtils.addMessageList(msg);
            } catch (IOException ex) {
                    /*
                    异常处理待优化
                     */
                ex.printStackTrace();
            }
        }
        else {
            ClientUtils.information_Alert("请先填写AI设置！");
        }
    }

    private static Message getAIReturnMessage() {
        Message msg = new Message();
        if(ServiceUtils.getChatUser().getUserName() == null) {
            msg.setSendUser(String.valueOf(ServiceUtils.getChatGroup().getGroupId()));
        }
        else {
            msg.setSendUser(ServiceUtils.getChatUser().getUserName());
        }
        msg.setReceiveUser(ServiceUtils.getSpeaker().getUserName());
        msg.setMsgType(MessageType.MESSAGE_SENTENCE_EXPLAIN);
        msg.setSendTime(LocalDateTime.now().format(formatter));
        msg.setContent("AI助手正在思考...");
        String id;
        if(ServiceUtils.getChatUser().getUserName() != null) {
            id = ServiceUtils.getChatUser().getUserName();
        }
        else {
            id = String.valueOf(ServiceUtils.getChatGroup().getGroupId());
        }
        msg.setId(id);
        msg.setCurrentDisplayIndex(0);
        msg.setAI(true);
        return msg;
    }

    private static Message getAskAIMessage(String content) {
        Message msg = new Message();
        AIUser ai = new AIUser();
        ai.setAI_ID(ServiceUtils.getSpeaker().getUserName());
        ai.setApi_key(APIKEY);
        if("DeepSeek".equals(AITYPE)) {
            ai.setAPI_URL(DEEPSEEK_URL);
        }
        else {
            ai.setAPI_URL(OPENAI_URL);
        }
        ai.setModel(MODEL);
        msg.setContent(ai.to_String(content));
        msg.setSendTime(LocalDateTime.now().format(formatter));

        //设置发送者为对方，因为AI消息显示会像对方的消息一样显示在左侧
        if(ServiceUtils.getChatUser().getUserName() == null) {
            msg.setSendUser(String.valueOf(ServiceUtils.getChatGroup().getGroupId()));
            msg.setId(ServiceUtils.getChatUser().getUserName());
        }
        else {
            msg.setSendUser(ServiceUtils.getChatUser().getUserName());
            msg.setId(String.valueOf(ServiceUtils.getChatGroup().getGroupId()));
        }
        msg.setReceiveUser(ServiceUtils.getSpeaker().getUserName());
        msg.setMsgType(MessageType.MESSAGE_SENTENCE_EXPLAIN);
        return msg;
    }
}
